import axios from "axios";
import { StorageService } from "@/utils/storage";
import { refreshToken } from "@/api/login";
import { useAuthStore } from "@/stores/auth";
import { API_BASE } from "@/utils/tools";
const REFRESH_CONFIG = {
  isRefreshing: false,
  requests: [],
  ignoreMsgs: ["无效的刷新令牌", "刷新令牌已过期"],
  isRelogin: false,
};

const service = axios.create({
  baseURL: API_BASE+'/api',
  timeout: 30000,
});

service.interceptors.request.use((config) => {
  if (import.meta.env.VITE_USE_BACK_DATA === "false") {
    return Promise.reject(
      Object.assign(new Error("取消请求"), { isAxiosCancel: true })
    );
  }

  const token = StorageService.get("Token");
  if (
    token &&
    !config.url.includes("/login") &&
    !config.url.includes("/captcha")
  ) {
    config.headers["Authorization"] = `Bearer ${token}`;
  }
  return config;
});

service.interceptors.response.use(
  async (response) => {
    const { code = 0, message, detail } = response.data;
    const msg = typeof message === "string" ? message : detail;

    if (code === 200) return response.data;

    if (code === 401) {
      const token = StorageService.get("refreshToken");
      if (!token) {
        showError(msg);
        return Promise.reject(msg);
      }
      return handleTokenRefresh(response.config);
    }

    showError(msg);
    return Promise.reject(msg);
  },
  (error) => {
    if (!error.isAxiosCancel) {
      if (error.response) {
        const { status, data } = error.response;
        if (status === 401) {
          return handleAuthError();
        }
        showError(data.message || `系统接口${status}异常`);
      } else {
        const errMsg = formatErrorMessage(error);
        showError(errMsg);
      }
    }
    return Promise.reject(error);
  }
);

async function handleTokenRefresh(failedRequest) {
  if (!REFRESH_CONFIG.isRefreshing) {
    REFRESH_CONFIG.isRefreshing = true;
    try {
      const result = await refreshToken();
      StorageService.set("Token", result.data.accessToken);
      REFRESH_CONFIG.requests.forEach((cb) => cb(result.data.accessToken));
      return retryRequest(failedRequest, result.data.accessToken);
    } catch (err) {
      return handleAuthError();
    } finally {
      REFRESH_CONFIG.isRefreshing = false;
      REFRESH_CONFIG.requests = [];
    }
  }

  return new Promise((resolve) => {
    REFRESH_CONFIG.requests.push((token) => {
      resolve(retryRequest(failedRequest, token));
    });
  });
}

function retryRequest(failedRequest, token) {
  const newRequest = { ...failedRequest };
  newRequest.headers.Authorization = `Bearer ${token}`;
  return service(newRequest);
}

async function handleAuthError() {
  if (!REFRESH_CONFIG.isRelogin) {
    REFRESH_CONFIG.isRelogin = true;
    try {
      await showReloginDialog();
      // 可以在这里添加登出逻辑
      useAuthStore().clearAuthData();
      location.href = "/login";
    } finally {
      REFRESH_CONFIG.isRelogin = false;
    }
  }
  return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
}

function formatErrorMessage(error) {
  if (error.message === "Network Error") return "后端接口连接异常";
  if (error.message.includes("timeout")) return "系统接口请求超时";
  if (error.message.includes("Request failed with status code")) {
    return `系统接口${error.message.slice(-3)}异常`;
  }
  return error.message;
}

function showError(message) {
  if (window.$snackbar) {
    window.$snackbar({
      showCloseButton: false,
      text: message,
      snackbarProps: { color: "error", location: "top" },
    });
  }
}

function showReloginDialog() {
  // 实现重新登录对话框逻辑
  return Promise.resolve();
}

export const setSnackbarInstance = (instance) => {
  window.$snackbar = instance;
};

export default service;
